package com.loser.utils;

import com.loser.utils.trace.MDCUtil;
import com.loser.utils.trace.TraceUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;

/**
 * 异步工具
 *
 * @author alan
 * @date 2021/12/13 20:30
 */
public class TryUtil {

    private static final Logger log = LoggerFactory.getLogger(TryUtil.class);

    /**
     * 为不同的线程设置相同的 traceId
     */
    public static void tryExc(String traceId, Runnable runnable) {

        try {
            MDCUtil.setTraceId(traceId);
            runnable.run();
        } catch (Exception e) {
            log.error("tryExc throw a e", e);
        } finally {
            MDCUtil.removeTraceId();
        }

    }

    /**
     * 执行方法
     */
    public static void tryExc(Runnable runnable) {

        String traceId = MDCUtil.getTraceId();
        traceId = StringUtils.isEmpty(traceId) ? TraceUtil.getTraceId() : traceId;
        tryExc(traceId, runnable);

    }

}
